package com.zbxj.wyz.service;

import com.zbxj.wyz.domain.Essay;
import com.zbxj.wyz.domain.dto.EssayDto;

import com.zbxj.wyz.domain.dto.EssayToExamDto;
import com.zbxj.wyz.domain.dto.Result;
import com.zbxj.wyz.domain.dto.TrueOrFalseToExamDto;
import com.zbxj.wyz.mapper.EssayMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.List;
import java.util.Set;

@Service

public class EssayService {
    @Autowired
    RedisTemplate redisTemplate;

    @Autowired
    EssayMapper essayMapper;

    @Cacheable(cacheNames="EssayByCondition")
    public List<EssayDto> getEssayByCondition(String courseName, String essayDifficulty, String essayAudit ,String searchValue){

        return essayMapper.getEssayByCondition(courseName,essayDifficulty,essayAudit,searchValue);
    };

    //增
    public Result addEssay(Essay essay){
        if (essayMapper.addEssay(essay) > 0)
            return new Result().ok("增加简答题成功");
        else
            return new Result().serverError("增加简答题失败");
    }

    //删
    @CacheEvict(cacheNames="EssayByCondition")
    public Result deleteEssay(Essay essay){
        //删除redis中所有以ChoiceByCondition开头的key,目的是刷新缓存
        Set<String> keys = redisTemplate.keys("EssayByCondition*");
        if (!CollectionUtils.isEmpty(keys)) {
            redisTemplate.delete(keys);
        }

        //更新数据库
        if(essayMapper.deleteEssay(essay) > 0)
            return new Result().ok("软删除简答题成功");
        else
            return new Result().serverError("软删除简答题失败");
    }

    public Result updateEssay(Essay essay){
        if(essayMapper.updateEssay(essay) > 0)
            return new Result<>().ok("更新简答题成功");
        else
            return new Result().serverError("更新简答题失败");
    }
    public Result auditEssay(Essay essay){
        if (essayMapper.auditEssay(essay)>0)
            return new Result<>().ok("审核简答题成功");
        else
            return new Result<>().ok("审核简答题成功");
    }

    public Result getAllEssayToExam(String courseName, String essayDifficulty){
        List<EssayToExamDto> essayList = essayMapper.getAllEssayToExam(courseName, essayDifficulty);
        if(!essayList.isEmpty())
            return new Result().ok("获取选择题列表（试卷用途）成功",essayList);
        else
            return new Result().serverError("获取选择题列表（试卷用途）失败");
    }
}
